<template>
  <div class="left-bar">
    <div class="item gimbal">
      <Gimbal :isBtnDisabled="isBtnDisabled" @on-refresh="onRefresh"></Gimbal>
    </div>
    <div class="item preset">
      <span class="title">预置点</span>
      <div class="column-container">
        <div class="top">
          <el-table
            class="preset-table"
            ref="presetTable"
            :data="tableDataPreset"
            highlight-current-row
            @row-click="handlePresetRowClick"
          >
            <!-- <el-table-column type="index" width="160" label="ID">
            </el-table-column> -->
            <el-table-column
              show-overflow-tooltip
              prop="uid"
              label="ID"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="name"
              label="名称"
              min-width="150"
            >
            </el-table-column>
          </el-table>
          <div class="no-data" v-if="!tableDataPreset.length">暂无数据</div>
        </div>
        <div class="bottom">
          <div class="button-container">
            <div class="btn">
              <el-button
                type="primary"
                size="mini"
                @click="handlePresetSet"
                :disabled="isBtnDisabled"
                >设置</el-button
              >
            </div>
            <div class="btn">
              <el-button
                type="primary"
                size="mini"
                @click="handlePresetCall"
                :disabled="isBtnDisabled || !presetRow"
                >调用</el-button
              >
            </div>
            <div class="btn">
              <el-button
                type="primary"
                size="mini"
                @click="handlePresetClear"
                :disabled="isBtnDisabled || !presetRow"
                >清除</el-button
              >
            </div>
            <div class="btn">
              <el-button
                type="primary"
                size="mini"
                @click="handlePathSet"
                :disabled="isBtnDisabled"
                >巡航</el-button
              >
            </div>
            <div class="btn">
              <el-button
                type="primary"
                size="mini"
                @click="handleRecordStart"
                :disabled="isBtnDisabled"
                >开始</el-button
              >
            </div>
            <div class="btn">
              <el-button
                type="primary"
                size="mini"
                @click="handleRecordStop"
                :disabled="isBtnDisabled"
                >停止</el-button
              >
            </div>
          </div>
          <div v-if="currentVideo.cameraId" class="status">
            <span>当前状态：</span>
            <span>{{ cameraStatus[currentVideo.cameraId] }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="item" v-if="false">
      <span class="title">路径续航</span>
      <div class="row-container">
        <div class="left">
          <el-table
            class="path-table"
            ref="pathTable"
            :data="tableDataPath"
            highlight-current-row
            @row-click="handlePathRowClick"
          >
            <!-- <el-table-column type="index" width="80" label="ID">
            </el-table-column> -->
            <el-table-column
              show-overflow-tooltip
              prop="uid"
              label="ID"
              min-width="150"
            >
            </el-table-column>
            <el-table-column
              show-overflow-tooltip
              prop="name"
              label="路径名称"
              min-width="150"
            >
            </el-table-column>
          </el-table>
        </div>
        <div class="right">
          <div class="button-container">
            <div class="btn">
              <el-button
                type="primary"
                size="mini"
                @click="handlePathSet"
                :disabled="isBtnDisabled"
                >设置</el-button
              >
            </div>
            <div class="btn">
              <el-button
                type="primary"
                size="mini"
                @click="handlePathCall"
                :disabled="isBtnDisabled || !pathRow"
                >调用</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="item" v-if="false">
      <span class="title">轨迹记录</span>
      <div class="row-container">
        <div class="left-label" v-if="currentVideo.cameraId">
          <span>当前状态：</span>
          <span>{{ cameraStatus[currentVideo.cameraId] }}</span>
        </div>
        <div class="right-button-group">
          <el-button
            type="primary"
            size="mini"
            @click="handleRecordStart"
            :disabled="isBtnDisabled"
            >开始</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleRecordStop"
            :disabled="isBtnDisabled"
            >停止</el-button
          >
          <el-button
            type="primary"
            size="mini"
            @click="handleRecordRun"
            :disabled="isBtnDisabled"
            >运行</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { deletePreset, getPathById, getPresetList } from '@/api/camera';
import Gimbal from './Gimbal';
export default {
  name: 'LeftBar',
  components: { Gimbal },
  data() {
    return {
      // 预置点数据
      tableDataPreset: [],
      // 路径续航数据
      tableDataPath: [],
      presetRow: null,
      pathRow: null,
      // 记录路径巡航信息
      paths: {},
      cameraStatus: {}, // 存储每个摄像头的状态
      cameraTimers: {}, // 存储每个摄像头的定时器
    };
  },
  props: {
    isBtnDisabled: {
      type: Boolean,
      default: true,
    },
    cameraAllInfo: {
      type: Array,
      default: () => [],
    },
  },
  computed: {
    // 当前播放的视频
    currentVideo() {
      return this.$store.getters['playVideo/getCurrentPlayingVideo'];
    },
    // 配置信息
    config() {
      return this.$store.getters['websocketClient/config'];
    },
  },
  watch: {
    'currentVideo.id': {
      handler(newVal) {
        if (newVal) {
          this.presetRow = null;
          this.pathRow = null;
          this.getPresetName();
          // this.getPathName();
        } else {
          this.presetRow = null;
          this.pathRow = null;
          this.tableDataPreset = [];
          this.tableDataPath = [];
        }
      },
      immediate: true,
    },
    cameraAllInfo: {
      handler(newVal) {
        // 拿cameraAllInfo的cameraId作为键值
        newVal.forEach((item) => {
          this.$set(this.cameraStatus, item.cameraId, '未运行');
          this.$set(this.cameraTimers, item.cameraId, null);
        });
      },
      immediate: true,
    },
  },
  beforeDestroy() {
    // 遍历cameraStatus的key，清除对应的定时器
    Object.keys(this.cameraStatus).forEach((cameraId) => {
      clearInterval(this.cameraTimers[cameraId]);
      this.$store.dispatch('websocketClient/sendMessage', {
        ws_url: `${process.env.VUE_APP_WEBSOCKET_URL}/${cameraId}`,
        message: {
          cameraId: cameraId,
          command: this.config['btnCommand']['recordStop'],
        },
      });
    });
  },
  methods: {
    /**
     * 选中预置点行
     */
    handlePresetRowClick(row) {
      // const index = this.tableDataPreset.indexOf(row);
      this.presetRow = row;
      // this.$set(this.presetRow, 'index', index + 1);
      // console.log('选中预置点行', this.presetRow);
    },
    /**
     * 选中巡航路径行
     */
    handlePathRowClick(row) {
      // const index = this.tableDataPath.indexOf(row);
      this.pathRow = row;
      // this.$set(this.pathRow, 'index', index + 1);
      // console.log('选中路径巡航', this.pathRow);
    },
    /**
     * 预置点-设置
     */
    handlePresetSet() {
      this.$emit('preset-set');
      // this.$store.dispatch('websocketClient/sendMessage', {
      // ws_url: `${process.env.VUE_APP_WEBSOCKET_URL}/${this.currentVideo.cameraId}`,
      // message: {
      //   cameraId: this.currentVideo.cameraId,
      //   command: this.config['btnCommand']['presetSet'],
      // }});
    },
    /**
     * 预置点-调用
     */
    handlePresetCall() {
      if (this.presetRow === null) {
        this.$message.warning('请选择预置点');
        return;
      }
      this.$store.dispatch('websocketClient/sendMessage', {
        ws_url: `${process.env.VUE_APP_WEBSOCKET_URL}/${this.currentVideo.cameraId}`,
        message: {
          cameraId: this.currentVideo.cameraId,
          command: this.config['btnCommand']['presetCal'],
          data: this.presetRow,
        },
      });
    },
    /**
     * 预置点-清除
     */
    async handlePresetClear() {
      if (this.presetRow === null) {
        this.$message.warning('请选择预置点');
        return;
      }
      await this.handlePresetDelete(this.presetRow.id);
      await this.getPresetName();
    },
    /**
     * 路径续航-设置
     */
    handlePathSet() {
      this.$emit('path-set');
      // this.$store.dispatch('websocketClient/sendMessage', {
      // ws_url: `${process.env.VUE_APP_WEBSOCKET_URL}/${this.currentVideo.cameraId}`,
      // message: {
      //   cameraId: this.currentVideo.cameraId,
      //   command: this.config['btnCommand']['pathSet'],
      // }});
    },
    /**
     * 路径续航-调用
     */
    handlePathCall() {
      if (this.pathRow === null) {
        this.$message.warning('请选择路径巡航点');
        return;
      }
      this.$store.dispatch('websocketClient/sendMessage', {
        ws_url: `${process.env.VUE_APP_WEBSOCKET_URL}/${this.currentVideo.cameraId}`,
        message: {
          cameraId: this.currentVideo.cameraId,
          command: this.config['btnCommand']['pathCall'],
          data: this.pathRow,
        },
      });
    },
    /**
     * 轨迹记录-开始
     */
    async handleRecordStart() {
      const cameraId = this.currentVideo.cameraId;
      if (this.cameraStatus[cameraId] === '运行中') {
        return this.$message.warning('正在运行中');
      }
      await this.getPathInfo();
      if (this.paths[cameraId].presets.length === 0) {
        return this.$message.warning('请先设置路径巡航点');
      }
      // 定时发送指令，时间间隔为interval，循环path数组发送指定预置点
      const interval = this.paths[cameraId].interval * 1000;
      let index = 0;

      this.cameraTimers[cameraId] = setInterval(() => {
        if (index >= this.paths[cameraId].presets.length) {
          index = 0; // 重置索引，实现循环
        }

        const preset = this.paths[cameraId].presets[index];
        this.$store.dispatch('websocketClient/sendMessage', {
          ws_url: `${process.env.VUE_APP_WEBSOCKET_URL}/${cameraId}`,
          message: {
            cameraId: cameraId,
            command: this.config['btnCommand']['recordStart'],
            data: preset,
          },
        });

        index++; // 移动到下一个预置点
      }, interval);
      this.$set(this.cameraStatus, cameraId, '运行中');
    },
    /**
     * 轨迹记录-停止
     */
    handleRecordStop() {
      const cameraId = this.currentVideo.cameraId;
      if (this.cameraStatus[cameraId] === '未运行') {
        return this.$message.warning('未开始运行');
      }
      this.$set(this.cameraStatus, cameraId, '未运行');
      clearInterval(this.cameraTimers[cameraId]);
      this.$store.dispatch('websocketClient/sendMessage', {
        ws_url: `${process.env.VUE_APP_WEBSOCKET_URL}/${cameraId}`,
        message: {
          cameraId: cameraId,
          command: this.config['btnCommand']['recordStop'],
        },
      });
    },
    /**
     * 轨迹记录-运行
     */
    handleRecordRun() {
      this.$store.dispatch('websocketClient/sendMessage', {
        ws_url: `${process.env.VUE_APP_WEBSOCKET_URL}/${this.currentVideo.cameraId}`,
        message: {
          cameraId: this.currentVideo.cameraId,
          command: this.config['btnCommand']['recordRun'],
        },
      });
    },
    // 刷新摄像头list
    onRefresh() {
      this.$emit('on-refresh', this.currentVideo.id);
    },
    /**
     * 获取预置点名称数据
     */
    async getPresetName() {
      try {
        const param = {
          camera_id: this.currentVideo.id,
        };
        const res = await getPresetList(param);
        if (res.code === 200) {
          this.tableDataPreset = res.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    /**
     * 获取路径巡航名称数据
     */
    async getPathName() {
      try {
        const param = {
          camera_id: this.currentVideo.id,
        };
        const res = await getPathById(param);
        if (res.code === 200) {
          this.tableDataPath = res.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    /**
     * 删除预置点名称
     */
    async handlePresetDelete(id) {
      try {
        const param = {
          id: id,
        };
        const res = await deletePreset(param);
        if (res.code === 200) {
          this.$store.dispatch('websocketClient/sendMessage', {
            ws_url: `${process.env.VUE_APP_WEBSOCKET_URL}/${this.currentVideo.cameraId}`,
            message: {
              cameraId: this.currentVideo.cameraId,
              command: this.config['btnCommand']['presetClear'],
              data: this.presetRow,
            },
          });
          this.pathRow = null;
          this.$message.success('删除成功');
        }
      } catch (error) {
        console.log(error);
      }
    },
    /**
     * 获取路径巡航数据
     */
    async getPathInfo() {
      try {
        const param = {
          camera_id: this.currentVideo.id,
        };
        const res = await getPathById(param);
        if (res.code === 200) {
          if (res.data) {
            this.$set(this.paths, this.currentVideo.cameraId, res.data);
          } else {
            this.$set(this.paths, this.currentVideo.cameraId, {
              id: '',
              presets: [],
              interval: '',
            });
          }
        }
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.left-bar {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: column;
  padding: 10px 0;
  box-sizing: border-box;
}
.item {
  height: auto;
  width: 100%;
  font-size: 14px;
  color: #333;
  padding: 5px 0;
  // border: 1px solid #ccc;
  &.gimbal {
    height: 218px;
  }
  &.preset {
    height: calc(100% - 218px);
  }
  .title {
    display: flex;
    align-self: flex-start;
    padding: 5px;
    border-bottom: 1px solid #ccc;
    color: #8371e9;
    &::before {
      content: '';
      margin-right: 5px;
      width: 8px;
      height: 20px;
      background-color: #8371e9;
      border-radius: 5px;
    }
  }
}
.column-container {
  position: relative;
  height: calc(100% - 31px);
  display: flex;
  flex-direction: column;
  // justify-content: space-between;
  padding: 0 5px;
  margin-top: 10px;
  .button-container {
    margin-top: 8px;
    display: grid;
    grid-template-columns: repeat(3, 1fr); // 三列等宽
    grid-template-rows: repeat(2, auto); // 两行自适应高度
    // gap: 10px; // 行列间距
    justify-items: center; // 水平居中
    align-items: center; // 垂直居中
    height: 100%;
  }
  .no-data {
    position: absolute;
    top: calc(50% - 40px);
    left: 50%;
    transform: translate(-50%, -50%);
    color: #909399;
  }
}
.row-container {
  display: flex;
  justify-content: space-between;
  padding: 0 5px;
  margin-top: 10px;
  .right {
    width: 100%;
  }
  .button-container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100%;
  }
}

.left-label {
  display: flex;
  align-items: center;
}
.right-button-group {
  display: flex;
  justify-content: center;
  align-items: center;
}
// .btn + .btn {
//   margin-left: 20px;
// }
::v-deep .el-table .el-table__cell {
  padding: 8px;
}
::v-deep .el-table {
  height: 364px;
  overflow-y: auto;
  &::before {
    display: none;
  }
  .el-table__header-wrapper {
    position: sticky;
    top: 0;
    z-index: 1;
  }
  .el-table__empty-block {
    display: none;
  }
}
::v-deep .el-table__row.current-row {
  background-color: #a598f0;
  td {
    background-color: transparent !important;
  }
}
</style>
